package lab.dexter.bbsreader.managers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lab.dexter.bbsreader.ListBrowser;
import lab.dexter.bbsreader.ListManager;
import lab.dexter.bbsreader.NewSMTHHttpClient;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import lab.dexter.bbsreader.R;

public class FavoriteListManager  extends ListManager {
	
	public static final String PARAM_URL_PATH_PREFIX = "URL_PATH_PREFIX";
	
	private class ListItem {
		public String path;
		public String name;
		public boolean isFolder;
		
		public ListItem(String path_, String name_, boolean isFolder_) {
			path = path_;// for folder, keep everything after "act=list"
			name = name_;
			isFolder = isFolder_;
		}
		
		public String getSuffix(){
			if(isFolder) {
				return path;
			}
			else {
				Log.v("PATH", path);
				return path.substring(17);
			}
		}
	}
	
	private final String BASE_URL = "http://www.newsmth.net/atomic2.php";
	
	private final String REGEXP_ITEM = "<a\\s+href=\"([^\"]+?)\"\\s+target=\"_.+?\">(.+?)</a>";
	
	private Pattern patternListItem;
	private String target;
	private String pathPrefix;
	
	private List<ListItem> listItems;
	
	public FavoriteListManager(Context context, Intent intent) {
		super(context, intent);
		listItems = new ArrayList<ListItem>();
		patternListItem = Pattern.compile(REGEXP_ITEM);
		pathPrefix = intent.getStringExtra(PARAM_URL_PATH_PREFIX);
		target = BASE_URL + pathPrefix;
	}

	@Override
	public boolean onItemClick(int position) {
		Intent intent = new Intent(mContext, ListBrowser.class);
		intent.setAction(Intent.ACTION_VIEW);
		
		ListItem item = listItems.get(position);
		if(item.isFolder) {
			intent.putExtra(ListBrowser.MGR, ListBrowser.MGR_FAVORITE_LIST);
			intent.putExtra(ClassifiedListManager.PARAM_URL_PATH_PREFIX, item.getSuffix());
		}
		else {
			intent.putExtra(ListBrowser.MGR, ListBrowser.MGR_BOARD_POSTS);
			intent.putExtra(BoardPostsManager.PARAM_BOARD, item.getSuffix());
			intent.putExtra(BoardPostsManager.PARAM_VIEW_MODE, BoardPostsManager.PARAM_VIEW_MODE_NORMAL);
		}
		mContext.startActivity(intent);
		return false;
	}

	@Override
	public int update() {
		try {
			NewSMTHHttpClient.getClient().fetchData(target, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public void dataProcessor(HttpEntity entity) {
		try {
			// stupid server massed up the charset header, so we do the decoding manually
			//content = EntityUtils.toString(entity);
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
			Matcher matcher = patternListItem.matcher(builder.toString());
			
			listItems.clear();
			while(matcher.find()) {
				String path = matcher.group(1);
				String name1 = matcher.group(2);
				matcher.find();
				String name2 = matcher.group(2);
				boolean isFolder = path.substring(5).startsWith("fav");
				listItems.add(new ListItem(path, name1 + " " + name2, isFolder));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean areAllItemsEnabled() {
		return true;
	}

	public boolean isEnabled(int arg0) {
		return true;
	}

	public int getCount() {
		return listItems.size();
	}

	public Object getItem(int position) {
		return listItems.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public int getItemViewType(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if(view == null) {
			LayoutInflater vi = (LayoutInflater)(mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
            view = vi.inflate(R.layout.double_row_topic_item, null);
		}
		ListItem it = listItems.get(position);
		if(it != null) {
			TextView tv = (TextView)view.findViewById(R.id.title);
			
			if(tv != null) {
				tv.setText(it.name);
			}
			
			tv = (TextView)view.findViewById(R.id.meta_info);
			
			if (tv != null) {
				if(it.isFolder) {
					tv.setText("[目录]");
				}
				else {
					tv.setText("[版面]");
				}
			}
		}
		return view;
	}

	public int getViewTypeCount() {
		return 1;
	}
	
	@Override
	public String getTitleSuffix() {
		return "收藏";
	}
}
